/*
 * tle5012b_dma.c
 *
 *  Created on: Nov 27, 2024
 *      Author: Vinson
 */

#include "tle5012b_dma.h"
#include "utils.h"
#include "global_var.h"

/*
 * data: sen_rx_val[1]
 * safety work：sen_rx_val[0]
 */
static volatile uint16_t sen_rx_val[2] = {0};
static uint16_t sen_tx_val[2] = {0x8021, 0};

#define SEN_CNT		2

void encoder_isr_enable(void)
{
    __HAL_DMA_ENABLE(hspi1.hdmatx);
}

void encoder_isr_prepare(void)
{
    __HAL_DMA_DISABLE(hspi1.hdmarx);
    hspi1.hdmarx->Instance->CNDTR = SEN_CNT;
	//dst
    hspi1.hdmarx->Instance->CPAR = (uint32_t)&hspi1.Instance->DR;
	//src
    hspi1.hdmarx->Instance->CMAR = (uint32_t)sen_rx_val;
    __HAL_DMA_ENABLE(hspi1.hdmarx);

    __HAL_DMA_DISABLE(hspi1.hdmatx);
    hspi1.hdmatx->Instance->CNDTR = SEN_CNT;
    hspi1.hdmatx->Instance->CPAR = (uint32_t)&hspi1.Instance->DR;
    hspi1.hdmatx->Instance->CMAR = (uint32_t)sen_tx_val;
}

errorTypes readAngleValue(int16_t  *data)
{
	//gpio_set_value(&sen_cs, 1);
    uint16_t rawData = sen_rx_val[1];

    rawData = (rawData & (DELETE_BIT_15));

    //check if the value received is positive or negative
    if (rawData & CHECK_BIT_14)
    {
        rawData = rawData - CHANGE_UINT_TO_INT_15;
    }

    *data = rawData;

    return NO_ERROR;
}

errorTypes getAngleValue(double *angleValue)
{
    int16_t rawAnglevalue = 0;
    errorTypes checkError = readAngleValue(&rawAnglevalue);

    if (checkError != NO_ERROR)
    {
        return checkError;
    }

    /*改为弧度 */
    *angleValue = (_2PI / POW_2_15) * ((double)rawAnglevalue);

    /* 角度(-180,180)*/
    //*angleValue = (ANGLE_360_VAL / POW_2_15) * ((double)rawAnglevalue);

    return NO_ERROR;
}

